import { DataSet } from 'choerodon-ui/pro';
import {
  appServiceApi,
  ciTemplateJobGroupApiConfig,
  ciTemplateStepCategoryApiConfig,
  ciTemplateJobApi,
  ciTemplateStepApi,
  CONSTANTS,
} from '@choerodon/master';
import {
  CUSTOM_BUILD, MAVEN_BUILD, STEP_TEMPLATE, TASK_TEMPLATE,
} from '@/routes/app-pipeline/CONSTANTS';
import {
  handleOk,
} from '@/routes/app-pipeline/routes/app-pipeline-edit/components/pipeline-modals/build-modals/content';
import { ctyunApiConfig, ctyunApi } from '@/api';

const {
  LCLETTER_NUM,
} = CONSTANTS;

const handleValidatorName = async (v: any, t: any, l: any, configuration:string, id?: any) => {
  let res = true;
  if (l === 'project') {
    if (t === STEP_TEMPLATE) {
      res = await ciTemplateStepApi.checkProjectStepName(v, id);
    } else {
      return true;
    }
  } else if (l === 'organization') {
    if (t === TASK_TEMPLATE) {
      res = await ciTemplateJobApi.checkName(v, id);
    } else if (t === STEP_TEMPLATE) {
      res = await ciTemplateStepApi.checkOrgStepName(v, id);
    }
  } else if (t === TASK_TEMPLATE) {
    res = configuration
      ? await ctyunApi.checkJobName(v, id)
      : await ciTemplateJobApi.checkJobName(v, id);
  } else if (t === STEP_TEMPLATE) {
    res = configuration
      ? await ctyunApi.checkStepName(v, id)
      : await ciTemplateStepApi.checkStepName(v, id);
  }
  return !res ? '名称重复' : true;
};

// 单独的triggervalue的格式转换 目前单独用于cdchart的转换
const transformSubmitTriggerValue = (value: any) => {
  try {
    const res = JSON.parse(JSON.stringify(value));
    if (typeof res === 'string') {
      return res;
    }
    return res.filter((i: any) => i).join(',');
  } catch (e) {
    console.log(e);
    return value?.join(',');
  }
};

const transformSubmitData = (ds: any) => {
  const record = ds?.current;
  const result = {
    [mapping.name.name]: record?.get(mapping.name.name),
    [mapping.triggerType.name]: record?.get(mapping.triggerType.name),
    [mapping.triggerValue.name]: (function () {
      try {
        const res = JSON.parse(JSON.stringify(record?.get(mapping.triggerValue.name)));
        if (typeof res === 'string') {
          return res;
        }
        return res.filter((i: any) => i).join(',');
      } catch (e) {
        console.log(e);
        return record?.get(mapping.triggerValue.name)?.join(',');
      }
    }()),
    [mapping.groupId.name]: record?.get(mapping.groupId.name),
    [mapping.categoryId.name]: record?.get(mapping.categoryId.name),
    [mapping.type.name]: record?.get(mapping.type.name),
    [mapping.script.name]: record?.get(mapping.script.name),
    [mapping.tags.name]: record?.get(mapping.tags.name).join(','),
  };
  return result;
};

const setAppService = (data: any, aName: any) => {
  if (data?.type.includes('cd_chart_deploy')) {
    return data?.chartDeployCfg?.appServiceDTO;
  }
  return aName;
};

const transformLoadData = (data: any, appServiceName: any) => ({
  [mapping.name.name]: data?.[mapping.name.name],
  [mapping.type.name]: data?.[mapping.type.name],
  [mapping.groupId.name]: data?.[mapping.groupId.name],
  [mapping.categoryId.name]: data?.[mapping.categoryId.name],
  [mapping.appService.name]: setAppService(data, appServiceName),
  [mapping.triggerType.name]: data?.[mapping.triggerType.name],
  [mapping.triggerValue.name]: data?.[mapping.triggerValue.name]?.split(','),
  [mapping.script.name]: data?.[mapping.script.name],
  [mapping.tags.name]: data?.[mapping.tags.name]?.split(',') || '',
});

let triggerValueAxiosData: any = [];

const triggerTypeOptionsData = [{
  text: '分支类型匹配',
  value: 'refs',
}, {
  text: '正则匹配',
  value: 'regex',
}, {
  text: '精确匹配',
  value: 'exact_match',
}, {
  text: '精确排除',
  value: 'exact_exclude',
}];

const originTriggerValueData = [{
  value: 'master',
  text: 'master',
}, {
  value: 'feature',
  text: 'feature',
}, {
  value: 'bugfix',
  text: 'bugfix',
}, {
  value: 'hotfix',
  text: 'hotfix',
}, {
  value: 'release',
  text: 'release',
}, {
  value: 'tag',
  text: 'tag',
}];

const mapping: {
    [key: string]: any
} = {
  name: {
    name: 'name',
    type: 'string',
    required: true,
  },
  groupId: {
    name: 'groupId',
    type: 'string',
    label: '所属任务分组',
    textField: 'name',
    valueField: 'id',
  },
  categoryId: {
    name: 'categoryId',
    type: 'string',
    label: '所属步骤分类',
    textField: 'name',
    valueField: 'id',
  },
  type: {
    name: 'type',
    type: 'string',
    label: '模板维护方式',
    textField: 'text',
    valueField: 'value',
    options: new DataSet({
      data: [{
        text: '普通创建',
        value: MAVEN_BUILD,
      }, {
        text: '自定义脚本',
        value: CUSTOM_BUILD,
      }],
    }),
  },
  appService: {
    name: 'appServiceName',
    type: 'string',
    label: '关联应用服务',
    disabled: true,
  },
  triggerType: {
    name: 'triggerType',
    type: 'string',
    label: '匹配类型',
    textField: 'text',
    valueField: 'value',
    defaultValue: 'refs',
    options: new DataSet({
      data: triggerTypeOptionsData,
    }),
  },
  triggerValue: {
    name: 'triggerValue',
    type: 'string',
    label: '触发分支',
    multiple: true,
    textField: 'text',
    valueField: 'value',
    options: new DataSet({
      data: originTriggerValueData,
    }),
  },
  script: {
    name: 'script',
    type: 'string',
  },
  tags: {
    name: 'tags',
    type: 'string',
    label: 'Tags',
    multiple: ',',
    maxLength: 255,
    validator: (value: any) => {
      if (value) {
        const flag = LCLETTER_NUM.test(value);
        if (!flag) {
          return '编码只能由小写字母、数字、"-"组成，且以小写字母开头，不能以"-"结尾';
        }
        return true;
      }
      return true;
    },
  },
};

const Index = (
  appServiceId: any,
  data: any,
  level: any,
  handleJobAddCallback: any,
  advancedRef: any,
  projectId: any,
): any => {
  const {
    template,
    type,
    appService,
    id,
    configuration,
  } = data || {};
  return ({
    autoCreate: true,
    fields: Object.keys(mapping).map((key) => {
      const item = mapping[key];
      switch (key) {
        case 'triggerValue': {
          item.dynamicProps = {
            multiple: ({ record }: any) => record?.get(mapping.triggerType.name) !== 'regex',
          };
          if (type.includes('cd_')) {
            item.label = '版本类型';
            item.options = new DataSet({
              data: originTriggerValueData.filter((i) => i.value !== 'tag'),
            });
          }
          // item.options = new DataSet({
          //   paging: true,
          //   autoQuery: true,
          //   transport: {
          //     read: () => ({
          //       ...appServiceApiConfig.getBrachs(appServiceId),
          //     }),
          //   },
          // });
          break;
        }
        case 'appService': {
          item.disabled = !type.includes('cd_');
          item.required = (level === 'project' && !window.location.href.includes('project-pipeline-template')) || type.includes('cd_chart_deploy');
          item.dynamicProps = {
            type: ({ record }: any) => {
              if (!type.includes('cd_')) {
                return 'string';
              }
              return 'object';
            },
          };
          if (type.includes('cd_')) {
            item.textField = 'name';
            item.valueField = 'id';
            item.options = new DataSet({
              autoQuery: true,
              paging: true,
              transport: {
                read: (data1: any) => ({
                  url: `/devops/v1/projects/${projectId}/app_service/page_by_options?checkMember=true`,
                  method: 'post',
                  params: {
                    ...data1?.params,
                  },
                  data: {
                    params: [data1?.data?.name || ''],
                  },
                }),
              },
            } as any);
          }
          break;
        }
        case 'triggerType': {
          item.required = (level === 'project' && !window.location.href.includes('project-pipeline-template'));
          break;
        }
        case 'groupId': {
          item.required = template === TASK_TEMPLATE;
          if (level && level !== 'project') {
            if (level === 'organization') {
              item.options = new DataSet({
                autoQuery: true,
                paging: false,
                transport: {
                  read: () => ({
                    ...ciTemplateJobGroupApiConfig.getList(),
                  }),
                },
              });
            } else {
              item.label = configuration ? '所属任务分类' : '所属任务分组';
              item.options = new DataSet({
                autoQuery: true,
                paging: false,
                transport: {
                  read: () => (configuration ? ctyunApiConfig.getProjectList() : {
                    ...ciTemplateJobGroupApiConfig.getSiteList(),
                  }),
                },
              });
            }
          } else if (level === 'project') {
            item.options = new DataSet({
              autoQuery: true,
              paging: false,
              transport: {
                read: () => ({
                  // master的这个对象里没有这个接口定义
                  // ...ciTemplateJobGroupApiConfig.getProjectList(),
                }),
              },
            });
          }

          break;
        }
        case 'categoryId': {
          item.required = template === STEP_TEMPLATE;
          if (level && level !== 'project') {
            if (level === 'organization') {
              item.options = new DataSet({
                autoQuery: true,
                transport: {
                  read: () => ({
                    ...ciTemplateStepCategoryApiConfig.getSteps(),
                  }),
                },
              });
            } else {
              item.options = new DataSet({
                autoQuery: true,
                transport: {
                  read: () => (configuration ? ctyunApiConfig.getProjectSteps() : {
                    ...ciTemplateStepCategoryApiConfig.getSiteSteps(),
                  }),
                },
              });
            }
          } else if (level === 'project') {
            item.options = new DataSet({
              autoQuery: true,
              transport: {
                read: () => ({
                  // master的这个对象里没有这个接口定义
                  // ...ciTemplateStepCategoryApiConfig.getProjectSteps(),
                }),
              },
            });
          }

          break;
        }
        case 'name': {
          if (data?.template) {
            if (data?.template === TASK_TEMPLATE) {
              item.label = '任务模板名称';
            } else {
              item.label = '步骤模板名称';
            }
          } else {
            item.label = '任务名称';
          }
          item.maxLength = !data?.template ? 30 : 60;
          item.validator = async (value: string) => handleValidatorName(
            value,
            template,
            level,
            data?.configuration,
            data?.id,
          );
          break;
        }
        default: {
          break;
        }
      }
      return item;
    }),
    events: {
      create: async () => {
        if (appServiceId) {
          const res = await appServiceApi.getBrachs(appServiceId);
          triggerValueAxiosData = res.content.map((i: any) => ({
            text: i?.branchName,
            value: i?.branchName,
          }));
        }
      },
      update: ({
        name, value, record, dataSet,
      }: any) => {
        switch (name) {
          case mapping.triggerType.name: {
            if (value === triggerTypeOptionsData[0].value) {
              record.getField(mapping.triggerValue.name).options.loadData(originTriggerValueData);
            } else if (value !== triggerTypeOptionsData[1].value) {
              // eslint-disable-next-line no-param-reassign
              record.getField(mapping.triggerValue.name).options.loadData(triggerValueAxiosData);
            }
            break;
          }
          default: {
            break;
          }
        }
        if (!template) {
          handleOk({
            canWait: false,
            BuildDataSet: dataSet,
            level,
            template,
            advancedRef,
            handleJobAddCallback,
            type,
            appService,
            id,
            data,
          });
        }
      },
    },
  });
};

export default Index;
export {
  mapping,
  triggerTypeOptionsData,
  transformSubmitData,
  transformLoadData,
  transformSubmitTriggerValue,
};
